﻿using CacheManager.Core.Internal;
using System.Text.Json;

namespace K9Nano.Caching.CacheManager;

internal class SystemTextJsonSerializer : CacheSerializer
{
    private static readonly Type OpenGenericType = typeof(JsonCacheItem<>);

    private readonly JsonSerializerOptions _jsonSerializerOptions;

    public SystemTextJsonSerializer(JsonSerializerOptions jsonSerializerOptions)
    {
        _jsonSerializerOptions = jsonSerializerOptions;
    }

    public SystemTextJsonSerializer() : this(new JsonSerializerOptions(JsonSerializerDefaults.Web))
    {

    }

    protected override Type GetOpenGeneric()
    {
        return OpenGenericType;
    }

    protected override object CreateNewItem<TCacheValue>(ICacheItemProperties properties, object value)
    {
        return new JsonCacheItem<TCacheValue>(properties, value);
    }

    public override byte[] Serialize<T>(T value)
    {
        return JsonSerializer.SerializeToUtf8Bytes(value, _jsonSerializerOptions);
    }

    public override object? Deserialize(byte[] data, Type target)
    {
        return JsonSerializer.Deserialize(data, target, _jsonSerializerOptions);
    }
}